import React, { useState, useEffect } from 'react';
import { Table, Button, Space, Tag, Select, message, Spin, Tooltip, Drawer, Descriptions, Typography } from 'antd';
import { CheckOutlined, InfoCircleOutlined, DownOutlined } from '@ant-design/icons';
import { OrderDetail, OrderDetailItem, OrderStatus } from '@/types/order'; // 假设你有一个类型定义文件
import { merchantService } from '@/service/merchantService';
import { toast } from 'sonner';
import { formatDate } from '@/utils/dateformat';

const { Option } = Select;
const { Text } = Typography;

import { Pagination } from '@/types/pagination';

type FilterStatus = "all" | OrderStatus;


const statusMap: Record<OrderStatus, { label: string, color: string }> = {
  pending: { label: '待支付', color: 'blue' },
  paid: { label: '待发货', color: 'yellow' },
  shipped: { label: '已发货', color: 'blue' },
  delivered: { label: '已送达', color: 'blue' },
  completed: { label: '已完成', color: 'green' },
  cancelled: { label: '已取消', color: 'red' },
}



const Orders: React.FC = () => {
  // 订单列表
  const [orders, setOrders] = useState<OrderDetail[]>([]);

  const [loading, setLoading] = useState<boolean>(false);

  const [pagination, setPagination] = useState<Pagination>({
    pageNum: 1,
    pageSize: 10,
    totalSize: 0,
  });
  // 状态筛选
  const [filterStatus, setFilterStatus] = useState<FilterStatus>("all");

  // 订单详情抽屉
  const [drawerVisible, setDrawerVisible] = useState<boolean>(false);

  // 当前查看的订单
  const [currentOrder, setCurrentOrder] = useState<OrderDetail | null>(null);

  // 获取订单列表
  const fetchOrders = async (pageNum: number, pageSize: number, status: FilterStatus) => {
    setLoading(true);

    const orders = await merchantService.getOrders();

    if (!orders) {
      toast.error('获取订单列表失败');
      setLoading(false);
      return;
    }
    setOrders(orders);
    setPagination({
      ...pagination,
      pageNum,
      pageSize,
      totalSize: 1,
    });
    setLoading(false);
  };


  // 首次加载时获取订单列表
  useEffect(() => {
    fetchOrders(pagination.pageNum, pagination.pageSize, filterStatus);
  }, []);

  // 处理表格变化（分页）
  const handleTableChange = (pagination: any) => {
    fetchOrders(pagination.current, pagination.pageSize, filterStatus);
  };

  // 处理状态筛选变化
  const handleStatusChange = (status: FilterStatus) => {
    setFilterStatus(status);
    fetchOrders(1, pagination.pageSize, status);
  };

  // 处理发货操作
  const handleShip = async (orderId: number) => {
    setLoading(true);
    const response = await merchantService.shipOrder(orderId);
    if (!response) {
      message.error('发货操作失败');
      setLoading(false);
      return;
    }

    message.success('订单已发货');
    fetchOrders(pagination.pageNum, pagination.pageSize, "all"); // 重新获取订单列表

    setLoading(false);
  }

  // 查看订单详情
  const showOrderDetail = (order: OrderDetail) => {
    setCurrentOrder(order);
    setDrawerVisible(true);
  };

  // 订单状态标签
  const renderStatusTag = (status: OrderStatus) => {
    const { label, color } = statusMap[status]
    return (
      <Tag color={color}>
        {label}
      </Tag>
    );
  };





  // 表格列定义
  const columns = [
    {
      title: '订单编号',
      dataIndex: 'id',
      key: 'id',
      width: 150,
    },
    {
      title: '用户昵称',
      dataIndex: 'buyerName',
      key: 'buyerName',
      width: 120,
    },
    {
      title: '商品信息',
      dataIndex: 'items',
      key: 'items',
      width: 300,
      render: (items: OrderDetailItem[]) => {
        const displayItems = items.slice(0, 1);
        const moreCount = items.length - 1;

        return (
          <div>
            {displayItems.map((item, index) => (
              <div key={index}>
                {item.name} x {item.quantity}
              </div>
            ))}
            {moreCount > 0 && (
              <Tooltip title={items.slice(1).map((item, index) => (
                <div key={index}>{item.name} x {item.quantity}</div>
              ))}>
                <Text type="secondary">
                  还有 {moreCount} 件商品 <DownOutlined />
                </Text>
              </Tooltip>
            )}
          </div>
        );
      },
    },
    {
      title: '总金额(¥)',
      dataIndex: 'totalPrice',
      key: 'totalPrice',
      width: 100,
      render: (total: string) => `¥${total}`,
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render: renderStatusTag,
    },
    {
      title: '下单时间',
      dataIndex: 'createdAt',
      key: 'createdAt',
      width: 150,
      render: (createdAt: string) => formatDate(createdAt),
    },
    {
      title: '操作',
      key: 'action',
      width: 150,
      render: (_: any, record: OrderDetail) => {
        if (record.status === "paid") {
          return (
            <Space size="middle">
              <Button
                type="primary"
                icon={<CheckOutlined />}
                size="small"
                onClick={() => handleShip(record.id)}
              >
                发货
              </Button>
              <Button
                type="default"
                icon={<InfoCircleOutlined />}
                size="small"
                onClick={() => showOrderDetail(record)}
              >
                详情
              </Button>
            </Space>
          );
        } else {
          return (
            <Button
              type="default"
              icon={<InfoCircleOutlined />}
              size="small"
              onClick={() => showOrderDetail(record)}
            >
              详情
            </Button>
          );
        }
      },
    },
  ];

  return (
    <div className="p-6">
      <div className="mb-4 flex justify-between items-center">
        <h2 className="text-xl font-bold">订单管理</h2>
        <div className="flex items-center">
          <span className="mr-2">订单状态：</span>
          <Select
            value={filterStatus}
            onChange={handleStatusChange}
            style={{ width: 120 }}
          >
            <Option value="all">全部订单</Option>
            <Option value="paid">待发货</Option>
            <Option value="shipped">已发货</Option>
            <Option value="completed">已完成</Option>
          </Select>
        </div>
      </div>

      <Spin spinning={loading}>
        <Table
          dataSource={orders}
          columns={columns}
          rowKey="id"
          pagination={{
            current: pagination.pageNum,
            pageSize: pagination.pageSize,
            total: pagination.totalSize,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total) => `共 ${total} 条记录`,
          }}
          onChange={handleTableChange}
        />
      </Spin>

      {/* 订单详情抽屉 */}
      <Drawer
        title="订单详情"
        placement="left"
        width={500}
        onClose={() => setDrawerVisible(false)}
        open={drawerVisible}
      >
        {currentOrder && (
          <div>
            <Descriptions bordered column={1}>
              <Descriptions.Item label="订单编号">{currentOrder.id}</Descriptions.Item>
              <Descriptions.Item label="用户昵称">{currentOrder.buyerName}</Descriptions.Item>
              <Descriptions.Item label="订单状态">{renderStatusTag(currentOrder.status)}</Descriptions.Item>
              <Descriptions.Item label="下单时间">{formatDate(currentOrder.createdAt)}</Descriptions.Item>
              <Descriptions.Item label="总金额">¥{currentOrder.totalPrice}</Descriptions.Item>
            </Descriptions>

            <div className="mt-4">
              <h3 className="font-bold mb-2">商品明细</h3>
              <Table
                dataSource={currentOrder.items}
                rowKey="id"
                pagination={false}
                columns={[
                  { title: '商品名称', dataIndex: 'name', key: 'name' },
                  { title: '单价', dataIndex: 'price', key: 'price', render: (price: string) => `¥${price}` },
                  { title: '数量', dataIndex: 'quantity', key: 'quantity' },
                  { title: '小计', dataIndex: 'subTotalPrice', key: 'subTotalPrice', render: (subTotalPrice: string) => `¥${subTotalPrice}` },
                ]}
              />
            </div>

            {currentOrder.status === 'paid' && (
              <div className="mt-4 flex justify-end">
                <Button
                  type="primary"
                  icon={<CheckOutlined />}
                  onClick={() => {
                    handleShip(currentOrder.id);
                    setDrawerVisible(false);
                  }}
                >
                  确认发货
                </Button>
              </div>
            )}
          </div>
        )}
      </Drawer>
    </div>
  );
};


export default Orders;